package com.dimld.connect.server;

import com.dimld.connect.http.RequestPool;
import com.dimld.connect.websocket.WebSocketHandler;
import io.undertow.Undertow;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import static io.undertow.Handlers.*;

public class HttpServer implements Runnable {
    private final Logger   log = LoggerFactory.getLogger(HttpServer.class);
    private final int      port;
    private final Class<?> httpReaderClass;
    private final Class<?> wsReaderClass;
    private final int      timeout;
    private final String   serviceUUID;

    public HttpServer(int port, Class<?> httpReaderClass, Class<?> wsReaderClass, int timeout, String serviceUUID) {
        this.port = port;
        this.httpReaderClass = httpReaderClass;
        this.wsReaderClass = wsReaderClass;
        this.timeout = timeout;
        this.serviceUUID = serviceUUID;
    }

    public void run() {
        Thread.currentThread().setName("HttpServer");

        Undertow.Builder builder = Undertow.builder().addHttpListener(this.port, "0.0.0.0");
        builder.setWorkerThreads(100);
        Undertow         build   = null;
        if (httpReaderClass != null) {
            build = builder.setHandler(path().addPrefixPath("/", virtualHost(new RequestPool(httpReaderClass, timeout, serviceUUID)))).build();
            log.debug("HTTP服务启动，端口[{}]", this.port);
        } else if (this.wsReaderClass != null) {
            build = builder.setHandler(path().addPrefixPath("/wsapi", websocket(new WebSocketHandler(wsReaderClass, timeout, serviceUUID)))).build();
            log.debug("WEBSOCKET服务启动，端口[{}]", this.port);
        }
        if (build != null) {
            build.start();
        } else {
            log.error("初始失败");
        }
    }
}